<?php

namespace App\Api;
use PhalApi\Api;
//获取客户IP

class Payment extends Api {
    
    function get_client_ip(){
        if (isset($_SERVER['HTTP_CF_CONNECTING_IP'])) {//使用cloudflare 转发的IP地址
            $ip = $_SERVER['HTTP_CF_CONNECTING_IP'];
        } else {
            if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
                $ip = getenv('HTTP_CLIENT_IP');
            } elseif (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
                $ip = getenv('HTTP_X_FORWARDED_FOR');
            } elseif (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
                $ip = getenv('REMOTE_ADDR');
            } elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
                $ip = $_SERVER['REMOTE_ADDR'];
            }
        }
        return $ip;
    }
    
    function rand_client_ip(){
        $client_ip = '';
        for($i=0;$i<4;$i++){
            $client_ip .= mt_rand(1, 254).'.';
        }
        
        return substr($client_ip, 0, -1);
    }
    
    function filter($str){
        $str = trim($str);
        $str = str_replace("&", "&amp;", $str);
        $str = str_replace("\"", "&quot;", $str);
        $str = str_replace("<", "&lt;", $str);
        $str = str_replace(">", "&gt;", $str);
        $str = str_replace("'", "&#39;", $str);
        return $str;
    }
    
    function gen_dhpay_invoice_id() {
        // Create random token
        $string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

        $max = strlen($string) - 1;

        $token = '';

        for ($i = 0; $i < 18; $i++) {
            $token .= $string[mt_rand(0, $max)];
        }

        return md5(uniqid(md5(microtime(true)), true)) . $token;
    }
    
    function curl($url, $is_post = true, $data = array()) {
    	$curl = curl_init();
    	
    	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    	curl_setopt($curl, CURLOPT_FRESH_CONNECT, 1);
    	curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 30);
    	curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    	
    	if($is_post && sizeof($data)){           
    		$data_string = json_encode($data);
    		$headers = ['Expect: '.(strlen($data_string) >= 1048576 ? '100-Continue' : '')];
    		curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    		curl_setopt($curl, CURLOPT_POST, true);
    		curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
    	}elseif(!$is_post && sizeof($data)){
    		if(strpos($url, '?')){
    			$url = rtrim($url, '&').'&'.http_build_query($data);
    		}else{
    			$url = $url.'?'.http_build_query($data);
    		}
    	}
    	curl_setopt($curl, CURLOPT_URL, $url);
    	
    	$response = curl_exec($curl);
    	if (curl_errno($curl)) {
    		return false;
    	}
    	curl_close($curl);
    	return $response;
    }
    
    
    public function redirect_pay($amount,$orderid,$currency,$source=''){
        
	    $api_name = 'cuizhibo1';//接口用户名
        $api_sign = '1m8hdeWzkIkDmrVpHdfAkOjyTspFUmJrMjekSTTXsRcMHFB2s4DPxIh9hOULabwC4MAP5LcYztBv7KQlibLNICHwZK0c2JFpwhriWycT5uYS0rElgyOiS5IxBV73PouBNPjGqaundEQiXgun7KqU9t5mpq3XyU236DG8oQAnWhIgav3RLpZ06LE7DHGd9w8ezdbkaqlE6y4lQiZ0oo4V0FZvjAzxxgsSNGK9RW7xS1PtT8f3YARVN2o2WOfY14r1gzJjMFv6wcYBqluOCbfUGnfHnZMXevNtD9J51VmbKCJX';//接口签名密钥
        
        $goods = [
        	[
        				'name'   => 'zuanshi',
        				'price'  => $amount,
        				'qty'    => '1',
        				'model'  => '123',
        				'link'   => '产品链接',
        				'image'  => '产品图片链接',
        				'attr'   => [
        					['opt_name'=>'属性1', 'opt_value'=>'属性值1'],
        					['opt_name'=>'属性2', 'opt_value'=>'属性值2'],
        				],
        	]
        ];
        
        $data = array(
            'client_ip'       => $this->get_client_ip(),//访客IP
            'client_agent'    => $_SERVER['HTTP_USER_AGENT'],//浏览器信息
            'client_language' => $_SERVER['HTTP_ACCEPT_LANGUAGE'],//浏览器语言
            'order_no'      =>  $orderid,//网站订单号,64个字符内
            'invoice_id'    =>  $this->gen_dhpay_invoice_id(),//32位
            'currency'      =>  $currency,//货币
            'subject'       =>  '会员充值',//订单标题
            'body'          =>  json_encode($goods),//商品信息
            'success_uri'   =>  $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['SERVER_NAME'].'/phalapi/?service=Result.Rsuccess',//支付完成后返回的页面
            'return_uri'    =>  $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['SERVER_NAME'].'/phalapi/?service=Result.Rcancel',//取消支付返回页面
            'notify_url'    =>  $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['SERVER_NAME'].'/phalapi/?service=Result.Rnotify',//异步接收通知
            'first_name'    =>  'Bret',//客户姓
            'last_name'     =>  'Talbott',//客户名
            'email'         =>  'brettalbott62@gmail.com',//邮箱
            'telephone'     =>  '3167615536',//电话
            'address'       =>  '718 N. Halstead Rd.',//街道地址
            'city'          =>  'Halstead',//城市
            'country'       =>  'US',//国家
            'zip_code'      =>  '67056',//邮编
            'zone'          =>  'Kansas',//省
        	'payment_method'=>  'redirect_pay',
            'amount'        =>  $amount,//订单金额格式：100.00
            'username'      =>  $api_name,//接口用户名
            //'embedded'      =>  1,//内嵌
        	'bn'            => 'zencart',//填系统类型 zencart,opencart,wordpress,或其它自建站类型
        );
        //签名
        $hash_src = '';
        $hash_key = array('invoice_id', 'order_no');
        foreach ($hash_key as $key) {
            $hash_src .= $data[$key];
        }
        $hash_src = $hash_src . $api_sign;
        $hash = hash('sha256', $hash_src);// sha256 算法
        $data['token'] = strtoupper($hash);
        
        foreach ($data as $k=>$v){
            $data[$k] = $this->filter($v);
        }    
        $gateway  = 'https://net.mrphper.xyz/pay/create_payment';
        $response = $this->curl($gateway, true, $data);
        
        $result   = json_decode($response, true);
        if($response===false)
        	exit('Please try again.');
        
        
        if(isset($result['result']['url'])){
            if($result['result']['redirect']){//站外
                if(!empty($source)){
                    $update = \PhalApi\DI()->notorm->charge_user
 					->where('orderno', $orderid)
					->update( array('pay_no' => $result['result']['pay_no'] ));
					//var_dump($rs);exit;
                    $rs['info']['code'] = '0';
        			$rs['info']['results'] = $result['result']['url'];
        			return $rs;
                }else{
                    $update = \PhalApi\DI()->notorm->charge_user
 					->where('orderno', $orderid)
					->update( array('pay_no' => $result['result']['pay_no'] ));
                    @header('Location:'.$result['result']['url']);
                    exit;
                }
                
            }else{//内嵌
                return"
                <iframe id='checkoutIframe' src=".$result['result']['url']."style='width:100%;border:none;height:100%;'></iframe>
                    <script>
                    window.addEventListener('message', function (ev) {
                        var msg = ev.data;
                        messageHandle(msg);
                    }, false);
                    function messageHandle(msg){
                        if(msg.action=='SUCCESS'){
                            window.location.href='https://mrphper.site/demo/success.php';//成功页面
                        }else if(msg.action=='3d-begin'){
                    		window.location.href=msg.url;
                        }
                    }
                </script>";
            }
        }elseif($result['result']['msg']){
        	//支付请求失败
        	//exit($result['result']['msg']);
        	echo $response;
        }
	}
	
	public function succpay($amount,$orderid,$paytype,$currency){
	    $rs = array('code' => 0, 'msg' => '', 'info' => array());
	    $currency = strtolower($currency);
	    $params = [
	        'amount' => $amount,
	        'currency' => $currency,
	        'mchNo' => '2025063866',
	        'mchOrderNo' => $orderid,
	        'notifyUrl' => $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['SERVER_NAME'].'/phalapi/?service=Result.Snotify',
	        'returnUrl' => $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['SERVER_NAME'].'/phalapi/?service=Result.Sreturn',
	        'timestamp' => round(microtime(true) * 1000),
	        'signType'=>'MD5',
	        'wayCode' => $paytype,
	    ];
	    
	    $sign = $this->get_sign($params);
	    
	    $params['sign'] = $sign;
	    $url = 'https://www.succuspay.com/api/pay/create';
	    //var_dump($params);exit;
	    $response = $this->curl_post($url,$params);
	    //return $response;
	    //print_r($response);exit;
	    if($response['code'] == 0){
	        $update = \PhalApi\DI()->notorm->charge_user
 					->where('orderno', $orderid)
					->update( array('pay_no' => $response['data']['payOrderNo'] ));
	        $rs['info']['code'] = '0';
		    $rs['info']['results'] = $response['data']['cashierUrl'];
	    }else{
	        $rs['code'] = $response['errCode'];
			$rs['msg'] = \PhalApi\T($response['errMsg']);
	    }
	    return $rs;
	}
	
	public function curl_post($url, $data){
	    $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        
        // 默认Header配置
        $defaultHeaders = [
            'Content-Type: application/json',
        ];
        // $finalHeaders = array_merge($defaultHeaders, $headers);
        
        curl_setopt($ch, CURLOPT_HTTPHEADER, $defaultHeaders);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        
        // 安全配置
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        
        $response = curl_exec($ch);
        if(curl_errno($ch)) {
            throw new Exception(curl_error($ch));
        }
        curl_close($ch);
        return json_decode($response, true);
	}
	
	public function get_sign($params){
	    ksort($params);
	    //print_r(json_encode($params));
	    //$paramString = http_build_query($params)."&key=o48T7317RAY4Y8u48eCN411592algcg3";
	    $paramString = 'amount='.$params['amount'].'&currency='.$params['currency'].'&mchNo='.$params['mchNo'].'&mchOrderNo='.$params['mchOrderNo'].'&notifyUrl='.$params['notifyUrl'].'&returnUrl='.$params['returnUrl'].'&signType='.$params['signType'].'&timestamp='.$params['timestamp'].'&wayCode='.$params['wayCode']."&key=o48T7317RAY4Y8u48eCN411592algcg3";
	    //var_dump($paramString);
        $sign = strtoupper(md5($paramString));
        //var_dump($sign);
        return $sign;
	}
	

    	
    
}
